﻿using System;
using System.Drawing.Imaging;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml.Serialization;
using CloudShot.Utils;

namespace CloudShot
{
	[Serializable]
	public class StorageSettings : IXmlSerializable
	{
		public Type StorageType { get; set; }
		public ImageFormat ImageFormat { get; set; }
		public string FolderToSave { get; set; }

		#region IXmlSerializable

		public XmlSchema GetSchema()
		{
			return null;
		}

		public void ReadXml(XmlReader reader)
		{
			while (reader.NodeType == XmlNodeType.Element)
			{
				using (XmlReader inner = reader.ReadSubtree())
				{
					XElement root = XElement.Load(inner);
					
					//skip empty nodes and nodes with no elements
					if (root.IsEmpty || !root.HasElements)
					{
						reader.Skip();
						continue;
					}

					XElement element = root.Element("FolderToSave");
					if (element != null) FolderToSave = element.Value;

					element = root.Element("ImageFormat");
					if (element != null) ImageFormat = ImageFormatUtils.GetImageFormat(element.Value);

					element = root.Element("StorageType");
					if (element != null) StorageType = Type.GetType(element.Value);

					inner.Close();
				}

				reader.Skip();
				break;
			}
		}

		public void WriteXml(XmlWriter writer)
		{
			if (FolderToSave != null)
				writer.WriteElementString("FolderToSave", FolderToSave);

			writer.WriteElementString("ImageFormat", ImageFormat != null ? ImageFormat.ToString() : null);
			writer.WriteElementString("StorageType", StorageType != null ? StorageType.FullName : null);//лучше записывать как атрибут <StorageSettings Typу=Dropbox>
		}

		#endregion
	}
}

